package com.xiaohe.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaohe.common.utils.HttpUtils;
import com.xiaohe.gulimall.member.Exception.PhoneExistException;
import com.xiaohe.gulimall.member.Exception.UserNameExistException;
import com.xiaohe.gulimall.member.dao.MemberLevelDao;
import com.xiaohe.gulimall.member.entity.MemberLevelEntity;
import com.xiaohe.gulimall.member.vo.MemberLoginVo;
import com.xiaohe.gulimall.member.vo.MemberRegistVo;
import com.xiaohe.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohe.common.utils.PageUtils;
import com.xiaohe.common.utils.Query;

import com.xiaohe.gulimall.member.dao.MemberDao;
import com.xiaohe.gulimall.member.entity.MemberEntity;
import com.xiaohe.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo memberRegistVo) {
        MemberEntity memberEntity = new MemberEntity();

        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());

        //检查手机号和用户名是否唯一,为了让controller能感知异常，机场机制
        checkPhoneUnique(memberRegistVo.getPhone());
        checkUserNameUnique(memberRegistVo.getUserName());
        memberEntity.setUsername(memberRegistVo.getUserName());
        memberEntity.setMobile(memberRegistVo.getPhone());
        //对密码进行加密处理MD5加盐处理
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(memberRegistVo.getPassword());
        memberEntity.setPassword(encode);
        this.baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) {
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",phone);
        Integer count = this.baseMapper.selectCount(queryWrapper);
        if(count>0){
            throw new PhoneExistException();
        }

    }

    @Override
    public void checkUserNameUnique(String userName) {

        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userName);
        Integer count = this.baseMapper.selectCount(queryWrapper);
        if(count>0){
            throw new UserNameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {
        String username = memberLoginVo.getUsername();
        String password = memberLoginVo.getPassword();

        //去数据库查询
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username)
                .or()
                .eq("mobile",username);
        MemberEntity memberEntity = this.baseMapper.selectOne(queryWrapper);
        if(memberEntity!=null){
            //获取密码
            String DbPassword = memberEntity.getPassword();

            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, DbPassword);
            //密码正确
            if(matches){
                return memberEntity;
            }else {
                //密码错误
                return null;
            }
        }else {
            //登录失败
            return null;
        }

    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //注册和登录合并逻辑
        String uid = socialUser.getUid();
        //判断当前社交用户
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("social_uid",uid);
        MemberEntity member = this.baseMapper.selectOne(queryWrapper);
        if(member!=null){
            //该用户已经注册了
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setId(member.getId());
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.updateById(memberEntity);
            member.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return member;
        }else {
            //用户未注册
            MemberEntity memberEntity = new MemberEntity();
            try {
                //查询社交用户的社交信息
                HashMap<String, String> map = new HashMap<>();
                map.put("access_token",socialUser.getAccess_token());
                map.put("uid",socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), map);
                if(response.getStatusLine().getStatusCode() ==200){
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    //昵称
                    String name = (String) jsonObject.get("name");
                    String gender = (String) jsonObject.get("gender");
                    String img = (String) jsonObject.get("profile_image_url");
                    memberEntity.setNickname(name);
                    memberEntity.setGender("m".equals(gender)?1:0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            memberEntity.setSocialUid(socialUser.getUid());
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.insert(memberEntity);
            return memberEntity;
        }
    }
}